package com.common.util.web.directive;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.common.util.web.ContextHolder;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

public class FullPathDirective implements TemplateDirectiveModel {
	public void execute(Environment environment, Map params, TemplateModel[] templateModels,
			TemplateDirectiveBody templateDirectiveBody) throws TemplateException, IOException {
		String path = DirectiveUtils.getString("path", params);
		if ((path != null) && (path.toLowerCase().startsWith("http"))) {
			environment.getOut().write(path);
			return;
		}
		if ((path != null) && (!path.startsWith("/"))) {
			path = "/" + path;
		}
		environment.getOut().write(getBasePath(ContextHolder.getRequest()) + path);
	}

	private String getBasePath(HttpServletRequest request) {
		return request.getContextPath();
	}
}
